//
//  PublishMainTableViewController.m
//  cityStar
//
//  Created by apple on 14/12/13.
//  Copyright (c) 2014年 tiny. All rights reserved.
//

#import "PublishMainTableViewController.h"
#import "HTDefine.h"
#import "SideViewController.h"
#import "VideoPublishViewController.h"
#import "MakefitrndsReleaseViewController.h"
#import "CarpoolPublishViewController.h"
#import "RecruitmentPublishViewController.h"
#import "HomemakingViewController.h"
#import "LawPublishViewController.h"
#import "OtherPublishViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "selectDistrict.h"
#import "HomemakingNeedViewController.h"
#import "RIButtonItem.h"
#import "UIActionSheet+Blocks.h"
#import "MyPublishViewController.h"

@interface PublishMainTableViewController ()<CLLocationManagerDelegate>

@property (retain, nonatomic) CLLocationManager *locManager;
@property (nonatomic, assign) CLLocationCoordinate2D loc;

@end

@implementation PublishMainTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavBar];
    [self initViews];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 80, 0, 0);
    //初始化位置管理器
    self.locManager = [[CLLocationManager alloc]init];
    //设置代理
    self.locManager.delegate = self;
    //设置位置经度
    self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置每隔100米更新位置
    self.locManager.distanceFilter = 100;
    //开始定位服务
    [self.locManager startUpdatingLocation];
}
- (void)initNavBar{
    self.navigationItem.title = @"发布";
    
    UISwipeGestureRecognizer* recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    recognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:recognizer];

    UIButton * regBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 20)];
    regBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [regBtn setTitleColor:[UIColor colorWithWhite:0.151 alpha:1.000] forState:UIControlStateNormal];
    [regBtn setTitle:@"我的发布" forState:UIControlStateNormal];
//    [regBtn setTitle:@"完成" forState:UIControlStateSelected];
    regBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [regBtn setTitleColor:[UIColor colorWithRed:0.991 green:0.532 blue:0.303 alpha:1.000] forState:UIControlStateHighlighted];
    [regBtn addTarget:self action:@selector(myPublish) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * iHaveNewsBtnItem = [[UIBarButtonItem alloc]initWithCustomView:regBtn];
    self.navigationItem.rightBarButtonItem = iHaveNewsBtnItem;
    
    UIButton *btnSide = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [btnSide setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    [btnSide setImage:[UIImage imageNamed:@"more_touch"] forState:UIControlStateHighlighted];
    [btnSide addTarget:self action:@selector(sideMove) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *bbtmLeft = [[UIBarButtonItem alloc]initWithCustomView:btnSide];
    self.navigationItem.leftBarButtonItem = bbtmLeft;
}

-(void)viewWillAppear:(BOOL)animated
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >=7.0) {
        self.navigationController.navigationBar.translucent = NO; //禁止半透明毛玻璃效果
        self.navigationController.navigationBar.tintColor = kWhiteNavTitleColor; //返回按钮颜色
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor]; //bar背景颜色
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:kWhiteNavTitleColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:18]}; //标题颜色
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }else{
        [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]]; //bar背景颜色
        self.navigationController.navigationBar.translucent = NO;
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:kWhiteNavTitleColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:18]};
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }
}

#pragma mark - locationDelegate
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

//协议中的方法，作用是每当位置发生更新时会调用的委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //结构体，存储位置坐标
    self.loc = [newLocation coordinate];
    //    CLLocation *currentLocation = [INTULocationManager sharedInstance].currentLocation;
    
    NSString *postUrl  = [NSString stringWithFormat:@"%@%f/%f",KInterFace_location,self.loc.latitude,self.loc.longitude];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            NSString *str = response[@"value"][@"detail"][@"city_code"];
            [[NSUserDefaults standardUserDefaults]setObject:str forKey:@"city_code"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [self webRequest_citydataWithCityID:str];
        }else{
            
        }
    }];
}

//当位置获取或更新失败会调用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *errorMsg = nil;
    if ([error code] == kCLErrorDenied) {
        errorMsg = @"访问被拒绝";
    }
    if ([error code] == kCLErrorLocationUnknown) {
        errorMsg = @"获取位置信息失败";
    }
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Location"
                                                       message:errorMsg delegate:self cancelButtonTitle:@"Ok"otherButtonTitles:nil, nil];
    [alertView show];
}

-(void)webRequest_citydataWithCityID:(NSString *)sendeid
{
    NSString *getPul = @"";
    NSString *cityID = [KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID];
    if (cityID) {
        getPul = [NSString stringWithFormat:@"%@/%@",KInterface_getRegion,cityID];
    }else{
        getPul = [NSString stringWithFormat:@"%@/%@",KInterface_getRegion,sendeid];
    }
    [SVProgressHUD showWithStatus:@"请稍后..." maskType:SVProgressHUDMaskTypeClear];
    [HttpRequestManager getMethod:getPul parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            [SVProgressHUD dismiss];
            [[selectDistrict shardDistrictInfo]setClasscityArray:response[@"value"]];
        }else{
            DLog(@"%@",errMsg);
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

- (void)myPublish{
    MyPublishViewController *myPlishVC = [[MyPublishViewController alloc]init];
    [self.navigationController pushViewController:myPlishVC animated:YES];
}
- (void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer {
    [self sideMove];
    //    [self.view removeGestureRecognizer:recognizer];
}
- (void)sideMove{
    [[SideViewController shareVc] showLeftView];
}
- (void)initViews{
    self.tableView.backgroundColor = kBackgroundColor;
    
    self.tableView.sectionFooterHeight = 0;
    self.tableView.sectionHeaderHeight = 0;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- UITableViewDataSource Methods
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0){
        return 15;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView reloadData];
    switch (indexPath.row) {
        case 0:
        {
            CarpoolPublishViewController *carpoolPublishVC = [[CarpoolPublishViewController alloc]init];
            [self.navigationController pushViewController:carpoolPublishVC animated:YES];
        }
            break;
        case 1:
        {
            VideoPublishViewController *videoPublishVC = [[VideoPublishViewController alloc]init];
            [self.navigationController pushViewController:videoPublishVC animated:YES];
        }
            break;
        case 2:
        {
            RecruitmentPublishViewController *recruitPublishVC = [[RecruitmentPublishViewController alloc]init];
            [self.navigationController pushViewController:recruitPublishVC animated:YES];
        }
            break;
            
        case 3:
        {
            MakefitrndsReleaseViewController *makeFriendsVC = [[MakefitrndsReleaseViewController alloc]init];
            [self.navigationController pushViewController:makeFriendsVC animated:YES];
        }
            break;
        case 5:
        {
            RIButtonItem *cancelItem = [RIButtonItem itemWithLabel:@"取消"];
            
            RIButtonItem *giveServierItem = [RIButtonItem itemWithLabel:@"提供服务" action:^{
                HomemakingViewController *homemakingPublishVC = [[HomemakingViewController alloc]init];
                [self.navigationController pushViewController:homemakingPublishVC animated:YES];
            }];
            RIButtonItem *needServierItem = [RIButtonItem itemWithLabel:@"需要服务" action:^{
                HomemakingNeedViewController *homemakingneedPublishVC = [[HomemakingNeedViewController alloc]init];
                [self.navigationController pushViewController:homemakingneedPublishVC animated:YES];
            }];
            UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"选择服务类型" cancelButtonItem:cancelItem destructiveButtonItem:giveServierItem otherButtonItems:needServierItem, nil];
            [actionSheet showInView:self.view];
            
        }
            break;
        case 6:
        {
            LawPublishViewController *lawPublishVC = [[LawPublishViewController alloc]init];
            [self.navigationController pushViewController:lawPublishVC animated:YES];
        }
            break;
        case 8:
        {
            OtherPublishViewController *otherPublishVC = [[OtherPublishViewController alloc]init];
            [self.navigationController pushViewController:otherPublishVC animated:YES];
        }
            break;
        default:
            break;
    }
}

@end
